#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-09-04 17:07:57
    @email:332904234@qq.com
    @version:1.0
    @fileName:article.py
    @describe:
"""
import time
import datetime
from django.utils import timezone
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.generic import View
from django.db.models import F, Q
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from ad.models import ADModel, DetailAdModel
from article import models
from operation.models import UserClickArticle

from django.contrib.auth import get_user_model

# 从系统中获取自己定义的user表
User = get_user_model()


class IndexView(View):
    """
    博客主页
    """

    def get(self, request, *args, **kwargs):
        username = request.user or None
        user_obj = User.objects.filter(username=username).first()
        # 获取文章列表
        article_querySet = models.ArticleModel.objects.all().order_by('-create_at')
        # 根据当前用户获取点赞的博客id
        blog_id_query_set = UserClickArticle.objects.filter(user=user_obj).values('blog_id')
        blog_id_list = []
        for item in blog_id_query_set:
            blog_id_list.append(item['blog_id'])

        # 获取排序规则
        read_num = request.GET.get('read_num', '')
        if read_num:
            article_querySet = article_querySet.order_by('-read_num')

        # 获取分类
        category = request.GET.get('category', '')
        if category:
            article_querySet = article_querySet.filter(category__category=category)

        # 全文搜索
        key_word = request.GET.get('key_word', '')
        if key_word:
            article_querySet = article_querySet.filter(Q(title__icontains=key_word) | Q(content__icontains=key_word))

        # 更新时间
        update = request.GET.get('update', '')
        if update:
            article_querySet = article_querySet.order_by('-update_at')

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(article_querySet, 10, request=request)

        article_list = p.page(page)

        # 获取广告列表
        ad = ADModel.objects.filter(due_time__gt=timezone.now()).order_by('ad_order')
        return render(request, 'index.html', locals())


class ArticleDetail(View):
    """
    博客文章详情
    """

    def get(self, request, *args, **kwargs):
        article_id = kwargs.get('article_id', None)
        if article_id:
            article = models.ArticleModel.objects.filter(id=article_id).first()
            # 阅读数加1
            models.ArticleModel.objects.filter(id=article_id).update(read_num=F('read_num') + 1)
            detail_ad = DetailAdModel.objects.filter(article_id=article_id, due_time__gt=timezone.now()).order_by('ad_order')
            return render(request, 'article-detail.html', locals())
        else:
            return redirect('index')


class ArticleContent(View):
    """
    ajax获取文章内容
    """

    def get(self, request, *args, **kwargs):
        article_id = kwargs.get('article_id', None)
        if article_id:
            article = models.ArticleModel.objects.filter(id=article_id).first().content
            return JsonResponse({"article": article})
        else:
            return redirect('index')


class DeleteArticleView(View):
    """
    删除文章的视图类
    """

    def post(self, request, *args, **kwargs):
        username = request.user
        id = request.POST.get('id', None)
        # 如果当前用户为登录不让删除,登录的用户判断是有否有权删除
        if request.user.is_authenticated and id:
            author = models.ArticleModel.objects.filter(id=id).first().author
            if author == username:
                models.ArticleModel.objects.filter(id=id).delete()
                return JsonResponse({'code': 0, 'message': '删除成功'})
            else:
                return JsonResponse({'code': 1, 'message': '不能删除别人的文章'})
        else:
            return JsonResponse({'code': 1, 'message': '删除失败'})


class TopNavView(View):
    """
    导航栏
    """

    def get(self, request, *args, **kwargs):
        category_query_list = models.BlogCategoryModel.objects.all()
        category_list = []
        for item in category_query_list:
            category_list.append({'key': item.category, 'value': item.get_category_display()})

        return JsonResponse({'code': 0, 'category_list': category_list})
